// 先获取项目配置，并且设为全局变量
const CONFIG = require('./config/config.js')
global.CONFIG = CONFIG

// 再引入app.js需要的内容
const path = require('path')
// 中间件
const express = require('express')
const cors = require('cors')
const createError = require('http-errors')
const logger = require('morgan')
// 路由模块
const router = require('./router.js')

const app = express()

// 初始化一些通用页面模板
app.set('views', 'views')
app.set('view engine', 'jade')

// 初始化一些中间件功能
app.use(logger('dev'))
app.use(express.json())
app.use(express.urlencoded({ extended: false }))
app.use(express.static('public'))
// CORS跨域处理
app.use(cors({
  origin: ['http://localhost:8080'],
  methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
  alloweHeaders: ['Content-Type', 'Authorization']
}))

// 初始化路由
router.init(app)

// 捕获错误 catch 404 and forward to error handler
app.use((req, res, next) => {
  next(createError(404))
})

// 显示错误模板
app.use((err, req, res, next) => {
  // set locals, only providing error in development
  res.locals.message = err.message
  res.locals.error = req.app.get('env') === 'development' ? err : {}

  // render the error page
  res.status(err.status || 500)
  res.render('error')
})

// 应用异常捕获,我承认我是菜比,先这么处理吧
process.on('uncaughtException', (err) => {
  //打印出错误
  console.log(err)
  //打印出错误的调用栈方便调试,以后写一个日志类再记录到文件
  console.log(err.stack)
})

module.exports = app
